const fs = require('fs')
const path = require('path')

verifyToken = () => {
  return async (ctx, next) => {
    if(!!ctx.header.authorization){
      const token = ctx.header.authorization.split(' ')[1]
      let tokenKey,verifyToken
      try {
        tokenKey = fs.readFileSync(path.join(__dirname, '../assets/key/tokenKey.key'), 'utf-8',)
        verifyToken = require('jsonwebtoken').verify(token, tokenKey)
      } catch (error) {
        console.log('Token错误', error.message)
        ctx.body = { code: 1, message: 'token错误，请重新登录' }
      }
      if(verifyToken) {
        await next()
      }
    }else {
      ctx.body = { code: 1, message: '您未登录' }
    }
  }
}
module.exports = verifyToken